# YOLO推理服务Docker镜像

FROM python:3.11-slim

# 构建参数
ARG DOWNLOAD_MODELS=true
ARG MODEL_MIRROR=github

# 设置工作目录
WORKDIR /app

# 设置环境变量避免交互式安装
ENV DEBIAN_FRONTEND=noninteractive

# 安装系统依赖
RUN apt-get update && apt-get install -y \
    # 基础工具
    wget \
    curl \
    # OpenCV依赖 - 使用最兼容的包名
    libgl1 \
    libglib2.0-0 \
    libsm6 \
    libxext6 \
    libxrender-dev \
    libgomp1 \
    # 视频处理依赖
    ffmpeg \
    # 图像处理依赖
    libjpeg62-turbo-dev \
    libpng-dev \
    libtiff5-dev \
    && rm -rf /var/lib/apt/lists/* \
    && unset DEBIAN_FRONTEND

# 配置pip使用清华源
RUN mkdir -p /root/.pip
COPY pip.conf /root/.pip/pip.conf

# 复制依赖文件
COPY requirements.txt .

# 安装Python依赖
RUN pip install --no-cache-dir --upgrade pip && \
    pip install --no-cache-dir -r requirements.txt

# 复制模型下载脚本
COPY download_models.sh .
RUN chmod +x download_models.sh

# 条件下载YOLO模型文件
RUN if [ "$DOWNLOAD_MODELS" = "true" ]; then \
        echo "🤖 开始下载YOLO模型文件..."; \
        ./download_models.sh; \
    else \
        echo "⏭️ 跳过模型下载"; \
        mkdir -p models; \
    fi

# 复制应用代码
COPY yolo_inference_server.py .
COPY config.yaml .

# 设置环境变量
ENV PYTHONPATH=/app
ENV PYTHONUNBUFFERED=1
ENV YOLO_MODELS_PRELOADED=true

# 暴露端口
EXPOSE 8000

# 健康检查
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
    CMD curl -f http://localhost:8000/health || exit 1

# 启动命令
CMD ["python", "yolo_inference_server.py", "--host", "0.0.0.0", "--port", "8000"]
